{
 "cells": [
  {
   "cell_type": "markdown",
   "id": "4b6f10a7-1c95-4e3e-bb49-92fd5a5eb69e",
   "metadata": {},
   "source": [
    "# Codex on StrategyQA"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 1,
   "id": "c523fb7f-ee3a-46d3-9ba3-60272d234efe",
   "metadata": {},
   "outputs": [],
   "source": [
    "import openai\n",
    "import re\n",
    "import time\n",
    "import json\n",
    "\n",
    "import numpy as np\n",
    "\n",
    "from tqdm import tqdm\n",
    "from pprint import pprint\n",
    "from tenacity import retry, stop_after_attempt, wait_chain, wait_fixed"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 2,
   "id": "729ccb7e-0854-41ea-b9e5-239ee225ca5a",
   "metadata": {},
   "outputs": [],
   "source": [
    "openai.api_key = \"sk-\" # My own key"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 3,
   "id": "23999e36-8eb2-4375-ac4d-291611ecdcf0",
   "metadata": {},
   "outputs": [],
   "source": [
    "@retry(wait=wait_chain(*[wait_fixed(3) for i in range(3)] +\n",
    "                       [wait_fixed(5) for i in range(2)] +\n",
    "                       [wait_fixed(10)]))\n",
    "def completion_with_backoff(**kwargs):\n",
    "    return openai.Completion.create(**kwargs)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 4,
   "id": "8ea04b12-cc44-4f7a-b5e5-dc0517c7ae13",
   "metadata": {},
   "outputs": [],
   "source": [
    "train_data = json.load(open('data/strategyqa_train.json'))\n",
    "train_filtered = json.load(open('data/strategyqa_train_filtered.json'))\n",
    "train_data_paragraphs = json.load(open('data/strategyqa_train_paragraphs.json'))\n",
    "test_data = json.load(open('data/strategyqa_test.json'))\n",
    "dev_idx = np.load('data/dev_idx.npy')\n",
    "dev_data = [train_data[i] for i in dev_idx]"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 11,
   "id": "6a049e53-3968-4bd8-92da-c2f9dd4678dd",
   "metadata": {},
   "outputs": [],
   "source": [
    "def extract_ans(ans_model):\n",
    "    ans_model = ans_model.split('\\n')\n",
    "    ans = []\n",
    "    residual = []\n",
    "    for li, al in enumerate(ans_model):\n",
    "        ans.append(al)\n",
    "        if('answer is' in al):\n",
    "            break\n",
    "    residual = list(ans_model[li + 1:])\n",
    "    ans = '\\n'.join(ans)\n",
    "    residual = '\\n'.join(residual)\n",
    "    return ans, residual"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "71a49aea-272f-4990-8173-ea44c5ed0625",
   "metadata": {},
   "source": [
    "# Original Prompt Acc 73.12"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 5,
   "id": "42672099-9ad9-4abe-84d5-d7586f8c3ba6",
   "metadata": {},
   "outputs": [],
   "source": [
    "prompt_original_step = open('lib_prompt/prompt_original_step.txt').read()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 15,
   "id": "fcd0b57f-9cec-4b57-b31a-4aae350e580d",
   "metadata": {
    "tags": []
   },
   "outputs": [
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "100%|████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████| 800/800 [2:36:12<00:00, 11.72s/it]\n"
     ]
    }
   ],
   "source": [
    "acc = 0\n",
    "total = 0\n",
    "with open('outputs/dev_codex_original_step.txt', 'w') as fd:\n",
    "    for d in tqdm(dev_data):\n",
    "        q = d['question']\n",
    "        a = d['answer']\n",
    "        if(a is True): a = 'yes'\n",
    "        else: a = 'no'\n",
    "        \n",
    "        prompt_q = prompt_original_step + '\\nQ: ' + q + '\\n'\n",
    "        prompt_q += 'A:'\n",
    "\n",
    "        response = completion_with_backoff(model=\"code-davinci-002\", \n",
    "                                            prompt=prompt_q, \n",
    "                                            temperature=0, \n",
    "                                            max_tokens=256)\n",
    "\n",
    "        ans_model = response['choices'][0]['text']\n",
    "        ans_model, _ = extract_ans(ans_model)\n",
    "        fd.write('Q: %s\\nA_model:\\n%s\\nA:\\n%s\\n\\n' % (q, ans_model, a))\n",
    "        \n",
    "        ans_ = ans_model.split('answer is ')\n",
    "        if(len(ans_) > 1 and 'yes' in ans_[1]): ans_ = 'yes'\n",
    "        else: ans_ = 'no'\n",
    "        \n",
    "        if(ans_ == a): acc += 1\n",
    "        total += 1"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 16,
   "id": "fc6f4a37-3456-42a0-b09e-05283879c289",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Total 800 correct 585 acc 0.7312\n"
     ]
    }
   ],
   "source": [
    "print('Total %d correct %d acc %.4f' % (total, acc, acc / total))"
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3 (ipykernel)",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.8.13"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 5
}
